package com.star.ms.admin.service.impl.order;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.star.ms.admin.service.order.OrderService;
import com.star.ms.admin.service.product.CategoryService;
import com.star.ms.admin.service.product.ProductService;
import com.star.ms.common.dao.mapper.order.OrderMapper;
import com.star.ms.common.pojo.Order;
import com.star.ms.common.pojo.product.Category;
import com.star.ms.common.pojo.product.Product;
import com.star.ms.common.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.unit.DataUnit;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
        implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;
    @Override
    public IPage<Order> getOrderPageByCondition(int pageNum, int pageSize, Map<String, Object> condition) {
        return orderMapper.selectWithBuyerAndProviderByPage(new Page<>(pageNum, pageSize), condition);
    }

    @Override
    public boolean updateStatus(List<Long> orderIds, Integer status) {
        UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
        wrapper.in("order_id", orderIds).set("order_status", status);
        return this.update(wrapper);
    }

    @Override
    public Order getOrderWithAllById(Long orderId) {
        return orderMapper.selectWithBuyerAndProviderAndProduct(orderId);
    }

    @Override
    public Order addOrderByMap(Map<String, Object> map) {
        long productId = (int)map.get("productId");
        long providerId = (int) map.get("providerId");
        long buyerId = (long) map.get("buyerId");
        int number = (int) map.get("number");
        double price = Double.parseDouble(map.get("price").toString());
        System.out.println("productId: "+ productId);
        System.out.println("providerId: " + providerId);
        System.out.println("number: " + number);
        Order order = new Order();
        order.setProductId(productId);
        order.setBuyerId(buyerId);
        order.setPrice(price);
        order.setProviderId(providerId);
        order.setNumber(number);
        // 确认存货是否足够
        if(productService.checkStock(productId, number)){
            // 存货足够后在插入订单
            order.setCreateTime(DateUtil.now());
            return save(order) ? order : null;
        }
        else return null;
    }

    @Override
    public List<Order> getOrderListByUserId(Long userId, Integer status) {
        return orderMapper.selectOrderListByUserId(userId, status);
    }

    /**
     * 支付订单
     * @param orderId 订单号
     * @return 支付的结果
     */
    @Override
    public boolean payOrderById(Long orderId) {
        // 查询订单
        Order order = this.getOrderWithAllById(orderId);
        // 验证商品库存是否足够
        boolean flag = productService.checkStock(order.getProductId(), order.getNumber());
        // 商品足够的话 ，保持商品库存量的一致性
        if(flag){
            Product product = order.getProduct();
            // 计算购买后的库存量
            product.setStock(product.getStock() - order.getNumber());
            // 最后更新订单状态
            order.setStatus(1);
            // 记录结果
            flag = productService.updateById(product);
            flag &= orderMapper.updateById(order) > 0;
        }
        return flag;
    }
    @Override
    public boolean cancelOrderById(Long orderId) {
        Order order = this.getOrderWithAllById(orderId);
        return this.removeById(order);
    }

    @Override
    public List<Order> getCurrentOrders(Integer num) {
        return orderMapper.selectCurrentOrders(num);
    }

    @Override
    public Double countMoney() {
        return orderMapper.selectCountMoney();
    }


    /**
     * 根据商品的类型统计交易额
     * @return
     */
    @Override
    public Map<String, Object> countMoneyByCategory() {
        // 找出所有不同商品类型
        List<Category> categoryList = categoryService.list();
        List<Float> moneyList = new ArrayList<>(categoryList.size());
        // 统计每个商品类型的交易额
        for (Category category : categoryList) {
            Float sum = orderMapper.selectCountMoneyByCategoryId(category.getId());
            moneyList.add(sum == null ? 0f : sum);
        }
        List<Map<String, Object>> list = new ArrayList<>();
        assert categoryList.size() == moneyList.size();
        for(int i = 0; i < categoryList.size(); i++){
            HashMap<String, Object> map = new HashMap<>();
            map.put("name", categoryList.get(i).getName());
            map.put("value", moneyList.get(i));
            list.add(map);
        }
        return new HashMap<String, Object>(){{
            put("categoryName", categoryList);
            put("categoryCountMoney", moneyList);
            put("categoryMoneyMap", list);
        }};
    }
}
